package com.gs.netty.support;




import com.gs.netty.core.annotation.Interceptor;
import com.gs.netty.core.common.CommandConstants;
import com.gs.netty.core.interceptor.HandlerInterceptor;
import com.gs.netty.websocket.remoting.req.Request;
import org.springframework.util.ObjectUtils;

import java.util.*;

/**
 * 映射拦截器类
 */
public final class MappedInterceptor<Req,Response> implements HandlerInterceptor<Req, Response> {
    // 拦截器
    private final HandlerInterceptor handlerInterceptor;
    // 包含
    private List<String> includePatterns = new ArrayList<String>();
    // 排除
    private List<String> excludePatterns = new ArrayList<String>();

    public MappedInterceptor(HandlerInterceptor handlerInterceptor, Interceptor annotation) {

        this.handlerInterceptor = handlerInterceptor;

        String[] includes = annotation.includes();

        LinkedList<String> excludeList = CommandConstants.CP_COMMANDS();

        if(!ObjectUtils.isEmpty(includes)) {
            for (String include : includes) {
                excludeList.remove(include);
                includePatterns.add(include);
            }
        }

        String[] excludes = annotation.excludes();

        if(!ObjectUtils.isEmpty(excludes)) {

            for (String exclude : excludes) {
                excludePatterns.add(exclude);
            }

        }

        excludePatterns.addAll(excludeList);
    }

    public boolean matches(Req req) {
        String command = null;
        if (req instanceof Request) {
             Request request = (Request) req;
             command = request.getCommand();
        }else {
            return false;
        }


        if (!ObjectUtils.isEmpty(this.excludePatterns)) {
            // 排除的
            for (String adapter : this.excludePatterns) {

                if (adapter.equals(command)) {
                    // 证明该拦截器不适合该请求
                    return false;
                }
            }
        }
        if (ObjectUtils.isEmpty(this.includePatterns)) {
            return true;
        }
        for (String adapter : this.includePatterns) {
            if (adapter.equals(command)) {
                return true;
            }
        }
        return false;
    }

    public HandlerInterceptor getHandlerInterceptor() {
        return handlerInterceptor;
    }
}
